package com.neusoft.bigdata.hive;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.CommandNeedRetryException;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.SessionState;

public class HiveDemo {
	
	  public static void main(String[] args) throws  Exception {
		  jdbcMode();
	   }
	  
	  public static void driverMode() throws CommandNeedRetryException{
		   ArrayList<String> res = new ArrayList<String>();
	       // String sql = "SELECT * from hbase_table_metric limit 5";
		   String sql = "show tables";
	        Driver driver = new Driver(new HiveConf(SessionState.class));
	        CommandProcessorResponse ret = driver.run(sql);
	        try {
	            driver.getResults(res);
	        } catch(IOException e) {
	            e.printStackTrace();
	        }
	        driver.close();
	        System.out.println(driver.getMaxRows());
	        try {
	            System.out.println(driver.getSchema());
	            //System.out.println(driver.getThriftSchema());
	        } catch(Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }       
//	        System.out.println(res);
//	        System.out.println(ret);
	  }
	  
	  public static void jdbcMode() throws  Exception{
		   Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
	       String querySQL="select avg(cpuload) from hbase_table_metric where resourceid='0ce28057-2bf4-4df2-846b-9d2db4038ba8' and recordtime between 1319991055309 and 1319991655309";
	       
	        //Connection con = DriverManager.getConnection("jdbc:hive://10.4.44.102:10000/default", "", "");
	       Connection con = DriverManager.getConnection("jdbc:hive://10.4.44.102:10000/default", "", "");
	        //Connection con = DriverManager.getConnection("jdbc:hive://", "", "");
	        Statement stmt = con.createStatement();
	        long start = System.currentTimeMillis();
	        ResultSet res = stmt.executeQuery(querySQL);  
	        long end = System.currentTimeMillis();
	        System.out.println("");
	          while (res.next()) {
	            System.out.println("Result: "+res.getString(1));
	        }
	          
	          System.out.println("��ʱ��" + (end-start) + "ms");
	  }


}
